<template>
	<view class="msg-area-main" :style="style">
		<!-- 触发按钮 -->
		<view class="msg-area" @click.stop="toggleMenu">
			<view class="msg-area-showtext">
				<view class="msg-area-icon">
					<uni-icons type="location" size="18" color="#ffffff"></uni-icons>
				</view>
				<uni-badge v-if="isDot" :isDot="true" class="msg-area-badge" />
				<text class="msg-area-showtext-txt u-line-1">{{ showtext || '请选择' }}</text>
				<uni-icons type="right" size="18" class="icon" color="#ffffff" />
			</view>
		</view>

		<!-- 弹出层 -->
		<uni-popup ref="popup" type="left" @maskClick="showlist = false">
			<view class="msg-area-title-area">
				<view class="msg-area-title-item msg-area-left">
					<uni-icons type="star" size="20" color="#fff"></uni-icons>
					<text class="msg-area-title-area-txt" style="font-size: 40rpx">收藏管理</text>
				</view>
				<view class="msg-area-title-item msg-area-right">
					<uni-icons type="left" size="12" color="#fff"></uni-icons>
					<text class="msg-area-title-area-txt" style="font-size: 24rpx">左滑编辑</text>
				</view>
			</view>
			<view class="msg-area-menu-container" :style="{ height: windowHeight }">
				<!-- 当前定位项 -->
				<uni-swipe-action>
					<uni-swipe-action-item show="true" :right-options="locationOptions" @click="handerlove">
						<view class="msg-area-menu-item" @click="handleHere">
							<view class="msg-area-item-content">
								<view class="msg-area-name-container">
									<text :class="currIndex === -1 ? 'msg-area-active-text' : 'msg-area-name-text'">当前定位</text>
								</view>
								<view class="msg-area-badge-count" v-if="unreadCount > 0">
									<text class="msg-area-badge-txt">{{ count(unreadCount) }}</text>
								</view>
								<text class="msg-area-address-text">{{ address.long }}</text>
							</view>
							<view class="msg-area-item-star" @click.stop="handerlove">
								<uni-icons :type="isFavorite ? 'star-filled' : 'star'" size="20" color="#ffaa00" />
							</view>
						</view>
					</uni-swipe-action-item>
				</uni-swipe-action>

				<!-- 加载状态 -->
				<view class="msg-area-empty-loading" v-if="isLoading">
					<u-loading-icon mode="flower" />
				</view>

				<!-- 空状态 -->
				<view v-else-if="storeData.user.favorite.length === 0" class="empty-state">
					<text class="msg-area-empty-txt">暂无更多收藏点</text>
				</view>

				<!-- 收藏列表（滑动操作） -->
				<u-swipe-action v-else @click="selectItem(index)">
					<u-swipe-action-item
						:options="item.options"
						:index="index"
						v-for="(item, index) in favoriteList"
						:key="index"
						:name="index"
						@click="handleSwipeOption(index, item, $event)"
					>
						<view class="msg-area-menu-item">
							<view class="msg-area-item-content" @click="selectItem(index, item)">
						
								<view class="msg-area-name-container">
									<text :class="currIndex === index ? 'msg-area-active-text' : 'msg-area-name-text'">{{ item.name }}</text>
								</view>
								<view class="">
									<text class="msg-area-address-text">{{ item.address }}</text>
								</view>
							</view>

							<view class="msg-area-item-star">
								<uni-icons type="star-filled" size="20" color="#ffaa00" />
							</view>
						</view>
					</u-swipe-action-item>
				</u-swipe-action>
			</view>
		</uni-popup>
	</view>
</template>

<script>
const linli = uniCloud.importObject('linliChat', { customUI: true });
import { getGridCode } from '../utils/getSurroundingGrids';
import getIsFavorite from '../utils/getIsFavorite';

export default {
	name: 'MsgAreaList',
	props: {
		top: { type: String, default: '10rpx' },
		left: { type: String, default: '10rpx' },
		right: { type: String, default: 'auto' },
		bottom: { type: String, default: 'auto' },
		unreadCount: { type: Number, default: 0 }
	},
	data() {
		return {
			showtext: '',
			showlist: false,
			currIndex: -1,
			unreadMap: null,
			isLoading: false,
			isFavorite: false,
			favorite_id: '',
			windowHeight: ''
		};
	},
	computed: {
		// 合并定位样式（兼容NVue）
		locationOptions() {
			return [{ text: this.isFavorite ? '取消收藏' : '收藏', style: { backgroundColor: '#3c9cff' } }];
		},

		style() {
			return {
				position: 'fixed',
				zIndex: 100,
				top: this.top,
				left: this.left,
				right: this.right,
				bottom: this.bottom,
				padding: '0 10rpx',
				backgroundColor: 'transparent'
			};
		},

		// 未读红点判断
		isDot() {
			try {
				let total = 0;
				// 处理 unreadMap 为空的情况（直接返回 false，而非 0）
				if (!this.unreadMap || Object.keys(this.unreadMap).length === 0) {
					return this.unreadCount > 0; // 仅判断 unreadCount 是否大于 0
				}
				// 累加 unreadMap 中的未读数
				Object.keys(this.unreadMap).forEach((key) => {
					total += Number(this.unreadMap[key]?.count) || 0; // 增加可选链避免 undefined 报错
				});
				// 总未读 = map 中的和 + 额外的 unreadCount，判断是否大于 0（返回布尔值）
				return total + this.unreadCount > 0;
			} catch (e) {
				console.error('计算未读红点错误:', e); // 注意是 console.error 而非 console.err
				return false; // 异常时返回 false（不显示红点）
			}
		},

		// 从store获取数据
		storeData() {
			return this.$store.state.msg;
		},

		// 地址格式化
		address() {
			const res = this.storeData.address || {};
			if (typeof res !== 'object') {
				console.error('非法地址数据', res);
				return { short: '未明地址', long: '未明地址' };
			}
			return {
				short: res.address.length > 7 ? res.address.slice(-8).replace(/[()（）【】\[\]{}<> ,，.。]/g, '') :res.address ,
				long: res.address
			};
		},

		// 当前定位
		location() {
			return this.$store.state.msg.location || {};
		},

		// 处理滑动选项（兼容Vue/NVue）
		favoriteList() {
			return this.storeData.user.favorite.map((item) => ({
				...item,
				options: [
					{
						text: '置顶',
						style: { backgroundColor: '#3c9cff' }
					},
					{
						text: '删除',
						style: { backgroundColor: '#f9ae3d' }
					}
				]
			}));
		}
	},
	watch: {
		// 监听地址变化更新显示文本
		address: {
			handler(newVal) {
				
				const newLocation = {
					longitude: this.location.longitude,
					latitude: this.location.latitude
				};
				const favorites = this.storeData.user.favorite || [];
				const grid = getGridCode(newLocation);
				const idx = favorites.findIndex((item) => item.favorite_id === grid);
				this.showtext = idx === -1 ? this.address?.short : favorites[idx].name;
			},
			immediate: true
		},

		// 监听定位变化更新收藏状态
		location: {
			async handler(newVal) {
				if (!newVal) return;
				try {
					const res = await getIsFavorite(this.storeData.location || {}, this.storeData.user?.favorite || []);
					this.isFavorite = res.isFavorite;
					this.favorite_id = res.favorite_id || '';
				} catch (error) {
					console.error('获取收藏状态失败:', error);
				}
			},
			deep: true,
			immediate: true
		}
	},
	async mounted() {
	
		uni.$on('mainPageClickEven', () => {
			this.showlist = false;
		});
		const res = this.$store.state.msg.systemInfo;

		this.windowHeight = res.windowHeight * (750 / res.windowWidth) + 'rpx';
	},
	destroyed() {
		uni.$off('mainPageClickEven');
	},
	methods: {
		clickLocation(e) {
			console.log(e);
		},
		// 格式化未读数量
		count(num) {
			return num > 99 ? '99+' : num || 0;
		},

		// 切换菜单显示状态
		toggleMenu() {
			this.$refs.popup.open();
			this.showlist = !this.showlist;
			if (this.showlist) this.getPublicMsgCount();
		},

		// 选择收藏项
		async selectItem(index, item, event) {
			try {
				const locationCode = getGridCode(this.storeData.location);
				const targetLocationCode = getGridCode(item.location);
				this.$store.commit('msg/SET_isFly', locationCode === targetLocationCode);
				this.$store.commit('msg/SET_queryParam', { location: this.storeData.location, id: '', type: 'public' });

				uni.setStorageSync(item.favorite_id, Date.now());
				this.currIndex = index;
				this.showtext = item.name;
				this.$store.commit('msg/SET_location', item.location);
				this.$refs.popup.close();
				this.$emit('item-selected', { index, value: item });

				} catch (err) {
				console.error('获取信息错误', err);
			}
		},

		// 处理滑动选项点击
		handleSwipeOption(index, item, event) {
			console.log(index, item, event);
			if (event.index === 1) {
				this.delFavorite(index, item);
			} else if (event.index === 0) {
				this.handleTop(index, item);
			}
		},

		// 置顶收藏项
		handleTop(index, item) {
			// 实现置顶逻辑（根据实际需求调整）
			const newList = [...this.storeData.user.favorite];
			const itemData = newList.splice(index, 1)[0];
			newList.unshift(itemData);
			this.$store.commit('msg/SET_user', {
				...this.storeData.user,
				favorite: newList
			});
			this.$emit('reLoadData');
		},


		// 切换到当前定位
		handleHere(e) {
			this.$store.commit('msg/SET_isFly', false);
			this.$store.commit('msg/SET_location', this.storeData.senderLocation);
			this.$store.commit('msg/SET_queryParam', { location: this.storeData.senderLocation, id: '', type: 'public' });
			this.$refs.popup.close();
			this.showtext = this.address.short;
		},

		// 处理当前定位收藏
		async handerlove() {
			try {
				await uni.showLoading({ title: '处理中...' });
				if (this.isFavorite) {
					// 取消收藏
					const res = await uni.showModal({
						title: '确认删除收藏点？',
						content: ''
					});
					if (res[1].confirm) {
						const result = await linli.favorite({
							favorite_id: this.favorite_id,
							action: 'remove',
							userId: this.storeData.user.userId,
							type: 'location'
						});
						if (result.code) {
							this.$store.commit('msg/SET_user', {
								...this.storeData.user,
								favorite: result.data.favorite
							});
							this.isFavorite = false;
							this.$emit('reLoadData');
						}
					}
				} else {
					// 添加收藏
					const res = await uni.showModal({
						title: '请输入收藏点名称(可选)',
						editable: true,
						placeholderText: this.showtext
					});
					if (!res[1].confirm) {
						return uni.showToast({ title: '已取消', icon: 'none' });
					}
					const name = res[1].content || this.showtext;
					const location = this.storeData.location;
					const result = await linli.favorite({
						userId: this.storeData.user.userId,
						favorite_id: getGridCode(location),
						action: 'add',
						type: 'location',
						address: this.storeData.address || '地址不明',
						name: name || '收藏点',
						location: location
					});
					if (result.code) {
						this.$store.commit('msg/SET_user', {
							...this.storeData.user,
							favorite: result.data.favorite
						});
						this.isFavorite = true;
						this.$emit('reLoadData');
					}
				}
			} catch (error) {
				console.error('收藏操作失败:', error);
				uni.showToast({ title: '操作失败', icon: 'none' });
			} finally {
				uni.hideLoading();
			}
		},

		// 删除收藏项
		async delFavorite(index, item) {
			try {
				console.log('删除前', this.storeData.user.favorite.length);
				const res = await uni.showModal({
					title: '确认删除收藏点？',
					content: item.name
				});
				if (res[1].confirm) {
					const result = await linli.favorite({
						favorite_id: item.favorite_id,
						action: 'remove',
						userId: this.storeData.user.userId,
						type: 'location'
					});
					if (result.code) {
						this.$store.commit('msg/SET_user', {
							...this.storeData.user,
							favorite: result.data.favorite
						});
						this.$emit('reLoadData');
						console.log('删除后', this.storeData.user.favorite.length);
					}
				}
			} catch (error) {
				console.error('删除收藏失败:', error);
				uni.showToast({ title: '删除失败', icon: 'none' });
			}
		}
	}
};
</script>

/* 命名空间前缀：msg-area-，避免全局冲突 */
<style lang="scss" scoped>

/* 主容器 */
.msg-area-main {
  position: fixed;
  z-index: 100;
  padding: 0 10rpx;
  background-color: transparent;
}
.msg-area-title-area {

 	display:flex;
	padding: 130rpx 30rpx 30rpx 30rpx;
   flex-direction: row;
   background-color: #55aaff;
}
.msg-area-title-item{
	display: flex;
	flex-direction: row;
}
.msg-area-title-area-txt{
	color: #fff;
	font-size: 30rpx;
}
.msg-area-left{
	flex:1;
}
.msg-area-right{
	display: flex;
	margin-right: 0;
	align-items: flex-end;

	}
.msg-area-showtext {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  height: 60rpx;
  line-height: 60rpx;
  padding: 0 10rpx;
  border-radius: 30rpx;
  background-color: #fff;
  border: 1px solid #eee;
  width: 300rpx;
   background-color: #55aaff;
}

/* 按钮文本 */
.msg-area-showtext-txt {
  font-size: 24rpx;
  font-weight: 600;
  color: #FFF;
  flex: 1;

  	/* #ifndef APP-PLUS-NVUE */
		white-space: nowrap;
	/* #endif */
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 图标 */
.msg-area-icon {
  font-size: 20rpx;
  color: #999;
  margin-left: 10rpx;
}

/* 弹出层容器 */
.msg-area-menu-container {
  padding: 10rpx 20rpx;
  flex: 1;
  flex-direction: column;
/* #ifndef APP-NVUE */
		box-sizing: border-box;
	/* #endif */
  width: 500rpx ;
  border-top-right-radius: 20rpx ;
}

/* 菜单项 */
.msg-area-menu-item {
  display: flex;
  flex-direction: row;
  align-items: center;
border-bottom: 1rpx solid #e5e5e5;
  padding: 15rpx 20rpx;

}
.msg-area-menu-item-active {
  background-color: #fafafa;
}

/* 内容区域 */
.msg-area-item-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10rpx;
  position: relative;
}


/* 激活文本 */
.msg-area-active-text {
  font-size: 24rpx;
  color: #2d81ff;
  font-weight: 500;
  margin-right: 10rpx;
}

/* 普通文本 */
.msg-area-name-text {
  font-size: 24rpx;
  color: #333;
  font-weight: 600;
}

/* 徽章 */
.msg-area-badge {
  width: 15rpx;
  height: 15rpx;
  position: absolute;
  top:0;
  right:0;
  border-radius: 15rpx;
  background-color: #ff557f;
  display: flex;
  align-items: center;
  justify-content: center;
}
.msg-area-badge-count {
  width: 30rpx;
  height: 30rpx;
  position: absolute;
  top:0;
  right:0;
  border-radius: 15rpx;
  background-color: #ff557f;
  display: flex;
  align-items: center;
  justify-content: center;
}
.msg-area-badge-txt {
  font-size: 20rpx;
  color: #fff;
}

/* 地址文本 */
.msg-area-address-text {
  font-size: 20rpx;
  color: #888;
  line-height: 26rpx;
  max-height: 52rpx;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 星星图标 */
.msg-area-item-star {
  padding: 10rpx;
  	/* #ifndef APP-NVUE */
   flex-shrink: 0;
  		/* #endif */

}

/* 空状态 */
.msg-area-empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 30rpx 0;
}
.msg-area-empty-txt {
  font-size: 22rpx;
  color: #999;
  margin-top: 10rpx;
}
.msg-area{
	display: flex;

	flex-direction: row;
}
/* 滑动组件样式（仅用单个类名，Weex 支持） */
.msg-area-swipe-action {
  flex: 1;
  flex-direction: column;
}
.msg-area-swipe-action-item {
  flex: 1;
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 15rpx 20rpx;
}
.msg-area-swipe-options {
  width: 160rpx;
  flex-shrink: 0;
}

/* Vue 专属样式 */
/*#ifndef APP-NVUE
.msg-area-showtext {
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  shadow-color: rgba(0, 0, 0, 0.05);
  shadow-offset: 0 2rpx;
  shadow-radius: 8rpx;

}
.msg-area-menu-container {
  height:100vh;
  background-color: #fff;
  border-radius: 16rpx;
   margin-top: -20rpx;
  border: 1px solid #eee;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
}
.msg-area-address-text {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  word-break: break-all;
}
	/*#endif*/

/* NVUE 专属样式 */
/* #ifdef APP-NVUE
/* 显式声明 flex 布局 */
.msg-area-main,
.msg-area-showtext,
.msg-area-menu-container,
.msg-area-menu-item,
.msg-area-item-content,
.msg-area-name-container {
  display: flex;

}
	/*#endif*/

/* 弹窗容器宽度与弹窗一致 */
.msg-area-menu-container {
  width: 500rpx;
  background-color: #fff;
  border-radius: 16rpx;
  margin-top: -20rpx;
  border: 1px solid #eee;
  	/* #ifndef APP-NVUE */
  	  shadow-color: rgba(0, 0, 0, 0.08);
  shadow-offset: 0 4rpx;
  shadow-radius: 16rpx;
  		/* #endif */

}
.msg-area-showtext {
		/* #ifndef APP-NVUE */
		  shadow-color: rgba(0, 0, 0, 0.05);
  shadow-offset: 0 2rpx;
  shadow-radius: 8rpx;
			/* #endif */


}
.msg-area-address-text {
	/* #ifndef APP-NVUE */
  white-space: normal;
	  		/* #endif */

  flex: 1;
}
/* 滑动选项按钮样式 */
.msg-area-swipe-options {
  height: 100%;
}

</style>
